﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Data.SQLite;

namespace SQLiteHelp
{
    public class AboutUs
    {
        public int ID { get; set; }
        public string Content { get; set; }
        public string MetaKeywords { get; set; }
        public string MetaDesc { get; set; }

        Database db = DatabaseFactory.CreateDatabase("SQLiteDB");

        public AboutUsDAO GetAboutUsByID()
        {
            string getContent = "Select content,meta_keywords,meta_desc from about_us where ID = 1";
            DbCommand cmd =db.GetSqlStringCommand(getContent);
            IDataReader reader = db.ExecuteReader(cmd);
            AboutUsDAO dao = new AboutUsDAO();
            if (reader.Read())
            {
                dao.Content = reader[0].ToString();
                dao.MetaKeywords = reader[1].ToString();
                dao.MetaDesc = reader[2].ToString();
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return dao;
        }

        public int UpdateAboutUs()
        {
            string getContent = "Select count(*) from about_us where ID = 1";
            DbCommand cmd = db.GetSqlStringCommand(getContent);
            int result = Convert.ToInt32(db.ExecuteScalar(cmd));
            int ret = 0;
            //不存在就插入数据
            if (result == 0)
            {
                string insertStr = "insert into about_us(ID,content,meta_keywords,meta_desc) values(1,@content,@key,@desc)";
                cmd = db.GetSqlStringCommand(insertStr);
                db.AddInParameter(cmd, "@content", DbType.String, Content);
                db.AddInParameter(cmd, "@key", DbType.String, MetaKeywords);
                db.AddInParameter(cmd, "@desc", DbType.String, MetaDesc);
                ret = db.ExecuteNonQuery(cmd);
            }
                //否则更新数据库
            else
            {

                string insertStr = "update about_us set content=@content,meta_keywords=@key,meta_desc=@desc where ID=1";
                cmd = db.GetSqlStringCommand(insertStr);
                db.AddInParameter(cmd, "@content", DbType.String, Content);
                db.AddInParameter(cmd, "@key", DbType.String, MetaKeywords);
                db.AddInParameter(cmd, "@desc", DbType.String, MetaDesc);
                ret = db.ExecuteNonQuery(cmd);
            }
            return ret;
        }
    }
    public class AboutUsDAO
    {
        public string Content { get; set; }
        public string MetaKeywords { get; set; }
        public string MetaDesc { get; set; }
    }
}
